package zy.controller.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;

import zy.controller.BaseController;
import zy.entity.sys.set.T_Sys_Set;
import zy.util.CommonUtil;
import zy.util.DateUtil;
import zy.util.ExportTxtUtil;
import zy.util.FormatterUtil;
import zy.util.StringUtil;

@Controller
@RequestMapping(value="common")
public class CommonController extends BaseController{
	
	@RequestMapping(value = "to_barcodeimport", method = RequestMethod.GET)
	public String to_barcodeimport() {
		return "common/barcodeimport";
	}

	@RequestMapping(value = "importTxt", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object importTxt(@RequestParam(required = true) MultipartFile txt,HttpServletRequest request,HttpSession session)
			throws IllegalStateException, IOException {
		File targetFile = new File(session.getServletContext().getRealPath(CommonUtil.IMPORT_TXT_PATH) + File.separator + "buy", DateUtil.getCurrentTimes() + ".txt");
		if (!targetFile.getParentFile().exists()){
			targetFile.getParentFile().mkdirs();
		}
		txt.transferTo(targetFile);
		Map<String, List<Map<String, Object>>> txtMap = UploadText(new FileInputStream(targetFile), getSysSet(session));
		return ajaxSuccess(txtMap);
	}
	
	public Map<String, List<Map<String, Object>>> UploadText(FileInputStream inputStream, T_Sys_Set set) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
		String splitChar = FormatterUtil.formatPandianSplitChar(set.getSt_blank());
		String str = null;
		Map<String, List<Map<String, Object>>> resultMap = new HashMap<String, List<Map<String, Object>>>();
		String[] strs = null;
		List<Map<String, Object>> okDatas = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> failDatas = new ArrayList<Map<String, Object>>();
		try {
			boolean hasOk = false;
			Map<String, Object> item = null;
			while ((str = reader.readLine()) != null) {
				if("".equals(str)){
					continue;
				}
				strs = str.split(splitChar);
				item = new HashMap<String,Object>();
				if (strs.length == 1) {
					item.put("barCode", strs[0]);
					item.put("amount", "");
					failDatas.add(item);
					continue;
				}
				item.put("barCode", strs[0]);
				item.put("amount", strs[1]);
				if (!strs[0].matches("[0-9a-zA-Z_-]*")) {
					failDatas.add(item);
					continue;
				}
				if (!strs[1].trim().matches("[0-9]*")) {
					failDatas.add(item);
					continue;
				}
				okDatas.add(item);
				hasOk = true;
			}
			reader.close();
			if (hasOk) {// 通过循环，把ok的数据进行同品数量累计处理
				Map<String, Integer> barcodeMap = new HashMap<String, Integer>();
				for (int i = 0; i < okDatas.size(); i++) {
					Map<String, Object> info = okDatas.get(i);
					if (!barcodeMap.containsKey(info.get("barCode"))) {
						barcodeMap.put(info.get("barCode").toString(), i);
					} else {
						int index = barcodeMap.get(info.get("barCode"));
						Map<String, Object> temp = okDatas.get(index);
						temp.put("amount", StringUtil.trimString(
								Integer.parseInt(StringUtil.trimString(temp.get("amount")))
								+ Integer.parseInt(StringUtil.trimString(info.get("amount")))));
						okDatas.remove(i);
						i--;
					}
				}
				resultMap.put("okdata", okDatas);
				resultMap.put("faildata", failDatas);
			} else {
				resultMap.put("okdata", okDatas);
				resultMap.put("faildata", failDatas);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		return resultMap;
	}

	@RequestMapping(value = "export_fail", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public void export_fail(String failJson,HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {
		List<Map> datas = JSONArray.parseArray(failJson, Map.class);
		List<String[]> list = new ArrayList<String[]>();
		for (Map item : datas) {
			list.add(new String[] { StringUtil.trimString(item.get("barCode")),
									StringUtil.trimString(item.get("amount")) });
		}
		ExportTxtUtil export = new ExportTxtUtil();
		export.writeTXT(DateUtil.getCurrentTimes()+".txt", list, request, response);
	}

}
